<?php

/**
 * emailparser.php
 * 07-07-09  
 * Parses an email forwarded by smtp2web.com through the use of a web hook
 * and uploads to a specified flickr account as well as logs data to a cametrics account.
 * Currently can work with email sent from yahoo, gmail, hotmail, outlook, iphone, andriod g1 email, picmessage (MMS) from verizon phones,
 * picmessage (MMS) from t-mobile phones, however, if you try to send a geo-tagged photo from a G1 it is resized and all EXIF data is
 * removed, so you must still include a Location tag in the body to add geo-tagging after message reception. Posted on android forums
	 * for a request to fix that on 7/14/09 : http://code.google.com/p/android/issues/detail?id=3251.
 * Still have to test with the other major providers like at&t pic message, etc...
 * 
 * Requires another service (like smtp2web.com) to use this script as a webhook callback URL which sends an SMTP email as RAW
 * POST DATA.
 * 
 * @author kmayoral
 */
require_once('_email_config.php');
require_once($PEL_LOC . '/PelJpeg.php');
require_once($CAMETRICS_HELPER_LOC . '/cametrics.helper.php');
// Change to this include once this service comes out of testing and we 
// want to store data in the real cametrics account
//require_once('../includes/cametrics.helper.php');
$str = file_get_contents("php://input");
$hasImage = false;
$logFile = $LOG;
$fh = fopen($logFile, 'a') or die("Can't open file");
fwrite($fh,date('r') . "\n");
fwrite($fh,"Parsing raw post...");
$strArr = parseRawPost($str);
//fwrite($fh,"\nRAWPOST:$str\n");
fwrite($fh,"done.\nParsing body of post...");
$bodyArr = parseBody($strArr['Body']);
//fwrite($fh,"done.\n");
$latitude = "0";
$longitude = "0";


if(array_key_exists('Location',$bodyArr)){
	//fwrite($fh,"Commencing geocoding procedure.\n");
	$geocode = geocodeByAddress($bodyArr['Location']);
	if($geocode){
		$latitude = $geocode[2];
		$longitude = $geocode[3];
		fwrite($fh,"LATLONG SET: (" . $latitude . "," . $longitude . ")\n" );
	}
} 


if(!empty($strArr)){
	$str = "";
	foreach ($strArr as $key=>$elem)
		{
			if($key == "Image"){
				if(strlen($elem) > 100){
					$str .= "[$key] = " . substr($elem,0,50) . "...(continues) <br>";
					fwrite($fh,"[$key] = " . substr($elem,0,50) . "...(continues) \n");
				}				
			}
			else{
				$str .= "[$key] = $elem <br>";
				fwrite($fh,"[$key] = $elem \n");
			}			
		}
		$fj = fopen("lastimage.jpg",'w') or die("Can't open image file");
		$fimagename = tempnam(sys_get_temp_dir(),"image.jpg");
		$fi = fopen($fimagename,"w") or die("Can't open image file");
		fwrite($fi, base64_decode($strArr['Image']));	
		fwrite($fj, base64_decode($strArr['Image']));
		fclose($fi);
		fclose($fj);

}
if(!empty($bodyArr)){
	$str = "";
	foreach ($bodyArr as $key=>$elem)
		{
			if($key == "Image"){
				if(strlen($elem) > 100){
					$str .= "[$key] = " . substr($elem,0,50) . "...(continues) <br>";
					fwrite($fh,"[$key] = " . substr($elem,0,50) . "...(continues) \n");
				}				
			}
			else{
				$str .= "[$key] = $elem <br>";
				fwrite($fh,"[$key] = $elem \n");
			}			
		}
}
if(getGpsInfo($fimagename,$info)){
	fwrite($fh,"\nLat/Lon retrieved from uploaded image: (". $info['Latitude'] . "," . $info['Longitude'] . ")\n");
	$latitude = $info['Latitude'];
	$longitude = $info['Longitude'];
}
else{
	fwrite($fh,"\nUploaded image is not geo-tagged.\n");
}

$username = getUserFromEmail($strArr['FromEmail']);
$groupname = getGroupFromEmail($strArr['FromEmail']);

if(!$username){
		$to      = $strArr['From'];
	$subject = 'Please associate this email address with your What\'s Invasive account';
	$message = "Dear user,\nThanks for your attempt at submitting an image through mobile@whatsinvasive.com. It seems that this email is not currently associated with any account on whatsinvasive.com or you have not yet activated your recently added email address. Please check your email for an activation email or login on the site and update your email associations in order to upload photos from this email address.  Without an association, we can not attribute an uploaded photo to any user, and as such we appreciate your cooperation. We look forward to receiving more entries from you in the future.\n\nSincerely,\nThe WhatsInvasive Team";
	$headers = 'From: mobile@whatsinvasive.com' . "\r\n" .
	    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
	    'X-Mailer: PHP/' . phpversion();
	fwrite($fh,"\nSending Email message:\nTO: " . $to . "\nSubject: " . $subject. "\nBody: " . $message);
	$mail_sent = mail($to, $subject, $message, $headers);
		if($mail_sent){
			fwrite($fh,"\nmail sent!\n");
		}
		else
			fwrite($fh,"\nmail delivery failed!\n");
	die();
}

if(!$hasImage){
	$to      = $strArr['From'];
	$subject = 'Error encountered in last submission';
	$message = "Dear $username,\nThanks for your attempt at submitting an image through mobile@whatsinvasive.com. We were unable detect an image in the previous email you've sent us and therefore could not complete the submission process. Please note that currently we only accept images in JPEG format. We look forward to receiving more entries from you in the future.\n\nSincerely,\nThe WhatsInvasive Team";
	$headers = 'From: mobile@whatsinvasive.com' . "\r\n" .
	    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
	    'X-Mailer: PHP/' . phpversion();
	fwrite($fh,"\nSending Email message:\nTO: " . $to . "\nSubject: " . $subject. "\nBody: " . $message);
	$mail_sent = mail($to, $subject, $message, $headers);
		if($mail_sent){
			fwrite($fh,"\nmail sent!\n");
		}
		else
			fwrite($fh,"\nmail delivery failed!\n");
	die();
}


// Create new phpFlickr object
//session_start();
require_once("$PHP_FLICKR_LOC/phpFlickr.php");

// This is for the test flickr account made by Keith M.
$f = new phpFlickr($FLICKR_API_KEY, $FLICKR_SECRET, true);
$f->setToken($FLICKR_TOKEN);

$f->auth('write');

$tags = $username . " " . $strArr['Subject'];
$type = substr(trim($strArr['Subject']),0,strpos(trim($strArr['Subject'])," "));
$dt = date("r");

	if(($latitude != "") and ($longitude != "") and ($latitude != "NaN") and ($longitude != "NaN") and ($latitude != "0") and ($longitude != "0"))
	{	
		
		//If X-Mailer tag is empty, or if it exists and doesn't contains the word "iPhone"
		//if(!isset($strArr['X-Mailer']) || strpos($strArr['X-Mailer'], "iPhone") === FALSE){  
			fwrite($fh,"\nadding gps info to image\n");      
			$fimagemodname = tempnam(sys_get_temp_dir(),"imagemod.jpg");
			addGpsInfo($fimagename, $fimagemodname, "", "", "", $longitude, $latitude, "", date("r"));
			fwrite($fh,"uploading (geoTagged) image to flickr");
			$response = $f->sync_upload($fimagemodname, (array_key_exists('Title',$bodyArr))?$bodyArr['Title']:$dt, ((array_key_exists('Description',$bodyArr))?$bodyArr['Description']:'') . "\n\n-Uploaded using the mobile@whatsinvasive.com email service.", $tags, 1, 1, 1);
			unlink($fimagemodname);
			fwrite($fh,"\nflickr response: " . $response . "\n");
			$to      = $strArr['From'];
			$subject = 'Thank you for your image submission';
			$message = "Dear $username,\nThanks for your submission, the image was successfully geotagged and uploaded to flickr and can be seen here: http://www.flickr.com/photos/39852345@N06/$response/\nWe look forward to receiving your submissions in the future and thank you again for your contribution.\n\nSincerely,\nThe WhatsInvasive Team";
			$headers = 'From: mobile@whatsinvasive.com' . "\r\n" .
			    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
			    'X-Mailer: PHP/' . phpversion();
			fwrite($fh,"\nSending Email message:\nTO: " . $to . "\nSubject: " . $subject. "\nBody: " . $message);
			$mail_sent = mail($to, $subject, $message, $headers);
			if($mail_sent){
				fwrite($fh,"\nmail sent!\n");
			}
			else
				fwrite($fh,"\nmail delivery failed!\n");
		//}	
		// If it's an iphone originating message, then the image is probably already geotagged, send it up to flickr
		/*else {
			fwrite($fh,"uploading (iPhone) image to flickr");
			$response = $f->sync_upload($fimagename, $dt, "", $tags, 1, 1, 1);
			if(getGpsInfo($fimagename,$gps_data)){
				$latitude = $gps_data['Latitude'];
				$longitude = $gps_data['Longitude'];
			}
			
			fwrite($fh,"\nflickr response: " . $response . "\n");
			$to      = $strArr['From'];
			$subject = 'Thank you for your image submission';
			$message = "Dear $username,\nThanks for your submission, the image was successfully uploaded to flickr and can be seen here: http://www.flickr.com/photos/39852345@N06/$response/\nSince your email originated from an iPhone, we assumed that the image had already been geo-tagged by the iPhone's camera. If this is not the case, you should update your settings on your iPhone to enable geo-tagging.\nWe look forward to receiving your submissions in the future and thank you again for your contribution.\n\nSincerely,\nThe WhatsInvasive Team";
			$headers = 'From: mobile@whatsinvasive.com' . "\r\n" .
			    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
			    'X-Mailer: PHP/' . phpversion();
			fwrite($fh,"\nSending Email message:\nTO: " . $to . "\nSubject: " . $subject. "\nBody: " . $message);
			mail($to, $subject, $message, $headers);
			fwrite($fh,"\nmail sent!\n");
		}*/

		
	}
	
	// If specified location wasn't valid, then just send the image up to flickr without geo tags
	else /*if(!isset($strArr['X-Mailer']) || strpos($strArr['X-Mailer'], "iPhone") === FALSE) */{
		fwrite($fh,"uploading (geoTagless) image to flickr");
		$response = $f->sync_upload($fimagename, (array_key_exists('Title',$bodyArr))?$bodyArr['Title']:$dt, ((array_key_exists('Description',$bodyArr))?$bodyArr['Description']:"") . "\n\n-Uploaded using the mobile@whatsinvasive.com email service.", $tags, 1, 1, 1);
		fwrite($fh,"\nflickr response: " . $response . "\n");
		$to      = $strArr['From'];
		$subject = 'Thank you for your image submission';
		$message = "Dear $username,\nThanks for your submission, although the image was successfully uploaded to flickr and can be seen here: http://www.flickr.com/photos/39852345@N06/$response/, we were unable to geo-tag it due to an unknown reason. \n\nMost likely, you forgot to provide a location within the body of your email using the format \nLocation:\"<address>\"\n where <address> is some parsable address like: \"Sepulveda Blvd and Venice Blvd\", or \"Staples Center\", or \"123 Any St Anytown, Anystate 90000\".\n\nProviding a location could be unnecssary if you used a GPS-enabled camera like the Nikon Coolpix 6000 or an iPhone to take your photos, so if that is the case, please make sure that GPS is enabled before taking another photo to submit to our site. \n\nWe look forward to receiving your submissions in the future and thank you again for your contribution.\n\nSincerely,\nThe WhatsInvasive Team";
		$headers = 'From: mobile@whatsinvasive.com' . "\r\n" .
		    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
		    'X-Mailer: PHP/' . phpversion();
		fwrite($fh,"\nSending Email message:\nTO: " . $to . "\nSubject: " . $subject. "\nBody: " . $message);
		$mail_sent = mail($to, $subject, $message, $headers);
		if($mail_sent){
			fwrite($fh,"\nmail sent!\n");
		}
		else
			fwrite($fh,"\nmail delivery failed!\n");
	}
	/*else{
		fwrite($fh,"uploading (iPhone) image to flickr");
		$response = $f->sync_upload($fimagename, $dt, "", $tags, 1, 1, 1);
		if(getGpsInfo($fimagename,$gps_data)){
				$latitude = $gps_data['Latitude'];
				$longitude = $gps_data['Longitude'];
		}
		fwrite($fh,"\nflickr response: " . $response . "\n");		
		$to      = $strArr['From'];
		$subject = 'Thank you for your image submission';
		$message = "Dear $username,\nThanks for your submission, the image was successfully uploaded to flickr and can be seen here: http://www.flickr.com/photos/39852345@N06/$response/\nSince your email originated from an iPhone, we assumed that the image had already been geo-tagged by the iPhone's camera. If this is not the case, you should update your settings on your iPhone to enable geo-tagging.\nWe look forward to receiving your submissions in the future and thank you again for your contribution.\n\nSincerely,\nThe WhatsInvasive Team";
		$headers = 'From: mobile@whatsinvasive.com' . "\r\n" .
		    'Reply-To: contact@whatsinvasive.com' . "\r\n" .
		    'X-Mailer: PHP/' . phpversion();
		fwrite($fh,"\nSending Email message:\nTO: " . $to . "\nSubject: " . $subject. "\nBody: " . $message);
		mail($to, $subject, $message, $headers);
		fwrite($fh,"\nmail sent!\n");		
	}*/
	Cametrics::measure($username.".contributions.location.all", $longitude.",".$latitude, 'location');
	Cametrics::measure($groupname.".contributions.location.all", $longitude.",".$latitude, 'location');
	Cametrics::measure("contributions.location.all", $longitude.",".$latitude, 'location');

	Cametrics::measure($username.".contributions.location.".$type, $longitude.",".$latitude, 'location');
	Cametrics::measure($groupname.".contributions.location.".$type, $longitude.",".$latitude, 'location');
	Cametrics::measure("contributions.location.".$type, $longitude.",".$latitude, 'location');

	Cametrics::measure("$groupname.contributions.location.$username.$type", $longitude.",".$latitude, 'location');
	Cametrics::measure("contributions.location.$username.$type", $longitude.",".$latitude, 'location');

	Cametrics::measure("$groupname.contributions.location.$username.all", $longitude.",".$latitude, 'location');
	Cametrics::measure("contributions.location.$username.all", $longitude.",".$latitude, 'location');	

	
	Cametrics::measure($username.".contributions.type", $type, 'string');
	Cametrics::measure($username.".contributions.time", $dt, 'datetime');

	Cametrics::measure($groupname.".contributions", $username, 'string');   
	Cametrics::measure($groupname.".contributions.type", $type, 'string');
	Cametrics::measure($groupname.".contributions.time", $dt, 'datetime');
	Cametrics::measure("contributions.group", $groupname, 'string');


	Cametrics::measure("contributions", $username, 'string');
	Cametrics::measure("contributions.type", $type, 'string');
	Cametrics::measure("contributions.time", $dt, 'datetime');


fclose($fh);
unlink($fimagename);

/**
 * parseRawPost takes in all the POST data sent from the smtp2web service and parses
 * all the relevant email data from it. From, FromEmail, Subject, Body, Image,
 * ImageType, ImageName,ImageEncoding, and X-Mailer are all currently parsed-for
 * values. You can add any other required data to be parsed for here.
 */
function parseRawPost($string){
	global $fh;
	global $hasImage;
	$strArr = array();
	//GET FROM AND TO
	if(!empty($_GET)){	
	foreach ($_GET as $key=>$elem)
		{
			$strArr[$key] = $elem;
		}

	}
	//GET FROM This is necessary now since we are having users send an email to mobile@whatsinvasive.com which forwards
	// the email to invasiveupload@smtp2web.com and so we can't get the original sender's email the normal way
	$start = strpos($string,"From:") + strlen("From:");
	$length = strpos($string,"\n",$start) - $start;
	$strArr['From'] = trim(substr($string,$start,$length));
	// GET EMAIL ADDRESS FROM "FROM" (sometimes it might be the case you get something like Bob Smith <bobbyboy@yahoo.com> for "FROM")
	$pattern = '/([a-z0-9])(([-a-z0-9._\+])*([a-z0-9]))*\@([a-z0-9])' . '(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+/i';
	preg_match($pattern,$strArr['From'],$matches);
	$strArr['FromEmail'] = $matches[0]; 
	
	//GET SUBJECT
	$start = strpos($string,"Subject:") + strlen("Subject:");
	$length = strpos($string,"\n",$start) - $start;
	$strArr['Subject'] = trim(substr($string,$start,$length));
	//GET BODY
	$after = strpos($string,"Content-Type: text/plain");
	// get substring of hexidecimal format "--000e03..." which goes before and after body 
	$substring = substr($string, 0, $after);
	$last = strrpos($substring,"\n--");
	$key = trim(substr($substring,$last,$after-$last));
	//$strArr['Key'] = $key;
	$start = strpos($string,"\n\n",$after);
	$length = strpos($string, $key,$start) - $start;
	$strArr['Body'] = trim(substr($string, $start,$length));
	//GET ATTACHMENT, IF THERE IS ONE
	if(strpos($string,"Content-Type: image/") !== FALSE){		
		$hasImage = true;
		$after = strpos($string,"Content-Type: image/");
		// get substring of hexidecimal format "--000e03..." which goes before and after body 
		$substring = substr($string, 0, $after);
		$last = strrpos($substring,"\n--");
		$after = strpos($substring,"\n",$last+3);
		$key = trim(substr($substring,$last,$after-$last));
		// get Image Type
		$start = $after + strlen("Content-Type: image/");
		$length = strpos($string, ";",$start) - $start;
		$strArr['ImageType'] = trim(substr($string,$start,$length));
		// get Image Name
		$start = strpos($string,"name=",$after) + strlen("name=");
		$length = strpos($string,"\n",$start) - $start;
		$strArr['ImageName'] = trim(substr($string,$start,$length), "\" \t\n\r\0\x0B");
		
		// get Image Encoding
		$start = strpos($string,"Content-Transfer-Encoding:",$after) + strlen("Content-Transfer-Encoding:");
		$length = strpos($string, "\n",$start) - $start;
		$strArr['ImageEncoding'] = trim(substr($string, $start,$length));
		// get Image Binary
		$start = strpos($string,"\n\n",$after);
//		fwrite($fh,"\nStart: " . $start);
		$length = strpos($string, $key,$after) - $start;
//		fwrite($fh,"\nlength: " . $length);
//		fwrite($fh,"\nkey: " . $key);
//		fwrite($fh,"\npre-trim: " . substr($string,$start,$length));
		$strArr['Image'] = trim(substr($string, $start,$length));
	}
	//Get X-Mailer to see what client sent the email message
	//Used to determine if the message came from an iPhone currently. Value will be of format: "iPhone Mail (7A341)"
	if(strpos($string,"X-Mailer:") !== FALSE){
		$start = strpos($string, "X-Mailer:") + strlen("X-Mailer:");
		$length = strpos($string, "\n",$start) - $start;
		$strArr['X-Mailer'] = trim(substr($string, $start,$length));
	}
	
	return $strArr;
}
/**
 * parseBody currently takes in the body section of the received smtp email and parses
	 * for a Location field by finding the address contained within Location:"<address>"
	* Any other fields can be included and searched for here. 
 */
function parseBody($body){
	global $fh;
	$bodyArr = array();
	fwrite($fh, "Parsing body...\n");
	$location_body = strpos($body, "Location:");
	if($location_body !== FALSE && $location_body !== ''){
		fwrite($fh, "Location field found at position '$location_body', parsing...");
		$start = $location_body + strlen("Location:");
//		fwrite($fh,"first start value:" . $start);
		//Find first occurence of " to delimit the location address
		$start = strpos($body, '"', $start) + 1;
//		fwrite($fh,"\nsecond start value:" . $start);
		//Find second occurence of " 
		$length = strpos($body,'"',$start) - $start;
//		fwrite($fh,"\nlength value:" . $length);
		$bodyArr['Location'] = trim(substr($body,$start,$length));		
		fwrite($fh, "\nLocation parsing complete: ". substr($body,$start,$length) .".\n");		
	}
	$description_body = strpos($body, "Description:");
	if($description_body !== FALSE && $description_body !== ''){
		fwrite($fh, "Description field found at position '$description_body', parsing...");
		$start = $description_body + strlen("Description:");
		//Find first occurence of " to delimit the location address
		$start = strpos($body, '"', $start) + 1;
		//Find second occurence of " 
		$length = strpos($body,'"',$start) - $start;
		$bodyArr['Description'] = trim(substr($body,$start,$length));		
		fwrite($fh, "\nDescription parsing complete: ". substr($body,$start,$length) .".\n");		
	}	
	$title_body = strpos($body, "Title:");
	if($title_body !== FALSE && $title_body !== ''){
		fwrite($fh, "Title field found at position '$title_body', parsing...");
		$start = $title_body + strlen("Title:");
		//Find first occurence of " to delimit the location address
		$start = strpos($body, '"', $start) + 1;
		//Find second occurence of " 
		$length = strpos($body,'"',$start) - $start;
		$bodyArr['Title'] = trim(substr($body,$start,$length));		
		fwrite($fh, "\nTitle parsing complete: ". substr($body,$start,$length) .".\n");		
	}
	return $bodyArr;
}

/**
 * Allows for the geocoding of an textual address by using the google provided geocoding
 * service. Any address that is parse-able in google maps should yield the same 
 * result here.
 */
function geocodeByAddress($address){
	/*
		 * Code borrowed from http://www.timshowers.com/2008/08/php-geocoding-tutorial-with-the-google-maps-api-part-one		
		 
	 */
	//Set up our variables
	$longitude = "";
	$latitude = "";
	$precision = "";
	global $fh;
	fwrite($fh,"geocoding address: " . $address . "...\n");
	//Three parts to the querystring: q is address, output is the format (
	//$key = "YOUR KEY HERE";
	$address = urlencode($address);
	$url = "http://maps.google.com/maps/geo?q=".$address."&output=csv";
	 
	$ch = curl_init();
	 
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER,0);
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	 
	$data = curl_exec($ch);
	fwrite($fh,"data returned by curl: " . $data . "\n");
	curl_close($ch);
	 
	//echo "Data: ". $data."<br>";
	//Check our Response code to ensure success
	if (substr($data,0,3) == "200")
	{
	$data = explode(",",$data);
	 
	$precision = $data[1];
	$latitude = $data[2];
	$longitude = $data[3];
	 
	//echo "Latutide: ".$latitude."<br>";
	 
	//echo "Longitude: ".$longitude."<br>";
	fwrite($fh,"success!\n");
	return $data;
	} else {
	//echo "Error in geocoding! Http error ".substr($data,0,3);
	fwrite($fh,"failure!\n");
	return FALSE;
	}	
}
/**
 * This function is useful for determining if the the JPEG image being checked is already geo
 * tagged or not. Returns FALSE if no GPS EXIF data exists, or true otherwise, filling
 * the provided $info array with the lat/lon data.
 */
function getGpsInfo($input,&$info){
	global $fh;
	$info = array();
	fwrite($fh,"In getGpsInfo\n");
	$jpeg = new PelJpeg($input);
	fwrite($fh,"PelJpeg created\n");	
	$exif = $jpeg->getExif();
	fwrite($fh,"Exif extracted\n");
	if(!$exif){
		fwrite($fh,"Exif == null\n");
		return FALSE;
	}
	$tiff = $exif->getTiff();
	fwrite($fh,"Tiff extracted\n");
	if(!$tiff){
		fwrite($fh,"Tiff == null\n");
		return FALSE;
	}
	$ifd0 = $tiff->getIfd();
	fwrite($fh,"Ifd extracted\n");
	if(!$ifd0){
		fwrite($fh,"Ifd == null\n");
		return FALSE;
	}
	$gps_ifd = $ifd0->getSubIfd(PelIfd::GPS);
	fwrite($fh,"GPSifd extracted\n");
	if(!$gps_ifd){
		fwrite($fh,"GPSifd== null\n");
		return FALSE;
	}
	$lat_ref = $gps_ifd->getEntry(PelTag::GPS_LATITUDE_REF)->getText();
    $lat = $gps_ifd->getEntry(PelTag::GPS_LATITUDE)->getValue();
    fwrite($fh,"\nLat_ref: $lat_ref Lat: $lat\n");    
    $lat = convertDMStoDecimal($lat[0][0]/$lat[0][1],$lat[1][0]/$lat[1][1],$lat[2][0]/$lat[2][1]);
    if($lat_ref == "S"){
    	$lat = -$lat;
    }
    $lon_ref = $gps_ifd->getEntry(PelTag::GPS_LONGITUDE_REF)->getText();
    $lon = $gps_ifd->getEntry(PelTag::GPS_LONGITUDE)->getValue();
	fwrite($fh,"\nLon_ref: $lon_ref Lon: $lon\n");    
	$lon = convertDMStoDecimal($lon[0][0]/$lon[0][1],$lon[1][0]/$lon[1][1],$lon[2][0]/$lon[2][1]);
    if($lon_ref == "W"){
    	$lon = -$lon;
    }
    $info['Latitude'] = $lat;
    $info['Longitude'] = $lon;
    fwrite($fh,"\n($lat,$lon)\n");
    return TRUE;
}

function addGpsInfo($input, $output, $description, $comment, $model,
                    $longitude, $latitude, $altitude, $date_time) {
  /* Load the given image into a PelJpeg object */
  global $fh;
  fwrite($fh,"In addGpsInfo\n");
  	$jpeg = new PelJpeg($input);

   
  
	
  /* Create and add empty Exif data to the image (this throws away any
   * old Exif data in the image). */

  $exif = new PelExif();

//  fwrite($fh,"Created new PelExif\n");
  $jpeg->setExif($exif);

  /* Create and add TIFF data to the Exif data (Exif data is actually
   * stored in a TIFF format). */

  $tiff = new PelTiff();

//  fwrite($fh,"Created new PelTiff\n");
  $exif->setTiff($tiff);

  /* Create first Image File Directory and associate it with the TIFF
   * data. */
  $ifd0 = new PelIfd(PelIfd::IFD0);
//  fwrite($fh,"Created new PelIfd IFD0\n");
  $tiff->setIfd($ifd0);

  /* Create a sub-IFD for holding GPS information. GPS data must be
   * below the first IFD. */
  $gps_ifd = new PelIfd(PelIfd::GPS);
//  fwrite($fh,"Created new PelIfd GPS\n");
  $ifd0->addSubIfd($gps_ifd);

  /* The USER_COMMENT tag must be put in a Exif sub-IFD under the
   * first IFD. */
  $exif_ifd = new PelIfd(PelIfd::EXIF);
//  fwrite($fh,"Created new PelIfd EXIF\n");
  $exif_ifd->addEntry(new PelEntryUserComment($comment));
  $ifd0->addSubIfd($exif_ifd);

  $inter_ifd = new PelIfd(PelIfd::INTEROPERABILITY);
//  fwrite($fh,"Created new PelIfd INTEROPERABILITY\n");
  $ifd0->addSubIfd($inter_ifd);

  $ifd0->addEntry(new PelEntryAscii(PelTag::MODEL, $model));
  $ifd0->addEntry(new PelEntryAscii(PelTag::DATE_TIME, $date_time));
  $ifd0->addEntry(new PelEntryAscii(PelTag::IMAGE_DESCRIPTION, $description));

  $gps_ifd->addEntry(new PelEntryByte(PelTag::GPS_VERSION_ID, 2, 2, 0, 0));

  /* Use the convertDecimalToDMS function to convert the latitude from
   * something like 12.34� to 12� 20' 42" */
  list($hours, $minutes, $seconds) = convertDecimalToDMS($latitude);
  fwrite($fh,"Converted latitude\n");

  /* We interpret a negative latitude as being south. */
  $latitude_ref = ($latitude < 0) ? 'S' : 'N';

  $gps_ifd->addEntry(new PelEntryAscii(PelTag::GPS_LATITUDE_REF,
                                       $latitude_ref));
  $gps_ifd->addEntry(new PelEntryRational(PelTag::GPS_LATITUDE,
                                          $hours, $minutes, $seconds));

  /* The longitude works like the latitude. */
  list($hours, $minutes, $seconds) = convertDecimalToDMS($longitude);
  fwrite($fh,"Converted longitude\n");
  $longitude_ref = ($longitude < 0) ? 'W' : 'E';

  $gps_ifd->addEntry(new PelEntryAscii(PelTag::GPS_LONGITUDE_REF,
                                       $longitude_ref));
  $gps_ifd->addEntry(new PelEntryRational(PelTag::GPS_LONGITUDE,
                                          $hours, $minutes, $seconds));

  /* Add the altitude. The absolute value is stored here, the sign is
   * stored in the GPS_ALTITUDE_REF tag below. */
  $gps_ifd->addEntry(new PelEntryRational(PelTag::GPS_ALTITUDE,
                                          array(abs($altitude), 1)));
  /* The reference is set to 1 (true) if the altitude is below sea
   * level, or 0 (false) otherwise. */
  $gps_ifd->addEntry(new PelEntryByte(PelTag::GPS_ALTITUDE_REF,
                                      (int)($altitude < 0)));

//fwrite($fh,"Created new JPEG from: " . $input . "\n$jpeg\n");
  /* Finally we store the data in the output file. */
  file_put_contents($output, $jpeg->getBytes());
}

function convertDMStoDecimal($deg,$min,$sec)
{

// Converts DMS ( Degrees / minutes / seconds ) 
// to decimal format longitude / latitude

    return $deg+((($min*60)+($sec))/3600);
}   

function convertDecimalToDMS($degree) {
  if ($degree > 180 || $degree < -180)
    return null;

  $degree = abs($degree);            // make sure number is positive
                                     // (no distinction here for N/S
                                     // or W/E).

  $seconds = $degree * 3600;         // Total number of seconds.

  $degrees = floor($degree);         // Number of whole degrees.
  $seconds -= $degrees * 3600;       // Subtract the number of seconds
                                     // taken by the degrees.

  $minutes = floor($seconds / 60);   // Number of whole minutes.
  $seconds -= $minutes * 60;         // Subtract the number of seconds
                                     // taken by the minutes.

  $seconds = round($seconds*100, 0); // Round seconds with a 1/100th
                                     // second precision.

  return array(array($degrees, 1), array($minutes, 1), array($seconds, 100));
}

function getUserFromEmail($email) {	
	global $fh, $DATABASE;
	fwrite($fh,"\nEmail received: " . $email);	
	fwrite($fh,"\nDB path: " . $DATABASE);
		
		$db = new PDO('sqlite:'.$DATABASE);
		fwrite($fh,"\nCreated PDO: sqlite");
		$sqlquery = "SELECT username,emailassociations.activated FROM user,emailassociations WHERE emailassociations.userid = user.ROWID and emailassociations.email = :email";
//$sqlquery = "SELECT username FROM user,emailassociations WHERE emailassociations.userid = user.ROWID and emailassociations.email = 'twinboykay@gmail.com'";
		$stmt = $db->prepare($sqlquery);
		fwrite($fh,"\nCreated statement: " . var_export_min($stmt,TRUE));
		//$stmt->bindParam(':email',$email,PDO::PARAM_STR,strlen($email));
		$stmt->execute(array(':email'=>$email));
		fwrite($fh,"\nexecuted statement");
		$res = $stmt->fetchAll();
		fwrite($fh, "\nGetting username from email: \n" . var_export_min($res[0],TRUE));
		if($res[0]['username']){
			if($res[0]['activated']){
				return $res[0]['username'];
			}
		}	
	return FALSE;
}
function getGroupFromEmail($email){
	global $fh, $DATABASE;
	//fwrite($fh,"\nEmail received: " . $email);
	//fwrite($fh,"\nDB path: " . $DATABASE);
		
		$db = new PDO('sqlite:'.$DATABASE);
		//fwrite($fh,"\nCreated PDO: sqlite");
		$sqlquery = "SELECT usergroup FROM user,emailassociations WHERE emailassociations.userid = user.ROWID and emailassociations.email = :email";
//$sqlquery = "SELECT username FROM user,emailassociations WHERE emailassociations.userid = user.ROWID and emailassociations.email = 'twinboykay@gmail.com'";
		$stmt = $db->prepare($sqlquery);
		//fwrite($fh,"\nCreated statement: " . var_export_min($stmt,TRUE));
		//$stmt->bindParam(':email',$email,PDO::PARAM_STR,strlen($email));
		$stmt->execute(array(':email'=>$email));
		//fwrite($fh,"\nexecuted statement");
		$res = $stmt->fetchAll();
		fwrite($fh, "\nGetting groupname from email: \n" . var_export_min($res[0],TRUE));
		if($res[0]['usergroup']){
			return $res[0]['usergroup'];
		}	
	return FALSE;
}
function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>
